import Router from '@koa/router';
import FileController from '@/controllers/FileController';
import { auth } from '@/middlewares';
import { upload } from '@/middlewares/upload';

const router = new Router({
  prefix: '/api/files',
});

/**
 * 文件管理路由
 */

// 上传单个文件
router.post(
  '/upload',
  auth,
  async (ctx, next) => {
    await new Promise((resolve, reject) => {
      upload.single('file')(ctx.req as any, ctx.res as any, (err: any) => {
        if (err) reject(err);
        else resolve(undefined);
      });
    });
    await next();
  },
  FileController.upload.bind(FileController)
);

// 批量上传文件
router.post(
  '/upload/multiple',
  auth,
  async (ctx, next) => {
    await new Promise((resolve, reject) => {
      upload.array('files', 10)(ctx.req as any, ctx.res as any, (err: any) => {
        if (err) reject(err);
        else resolve(undefined);
      });
    });
    await next();
  },
  FileController.uploadMultiple.bind(FileController)
);

// 获取文件列表
router.get(
  '/',
  auth,
  FileController.list.bind(FileController)
);

// 获取文件详情
router.get(
  '/:id',
  auth,
  FileController.getById.bind(FileController)
);

// 下载文件
router.get(
  '/:id/download',
  auth,
  FileController.download.bind(FileController)
);

// 删除文件
router.delete(
  '/:id',
  auth,
  FileController.delete.bind(FileController)
);

// 批量删除文件
router.post(
  '/batch-delete',
  auth,
  FileController.batchDelete.bind(FileController)
);

export default router;

